package com.danicsoft.daide.token;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Represents an integer as a token. An integer token is a token whose first two
 * bits are 0 and the remainder is encoded as 14 bit twos-compliment.
 * 
 * @author Daniel Yule (daniel.yule@gmail.com)
 * @version 1.0
 */
public class IntegerToken extends Token {

	/**
	 * The integer this integer token represents
	 */
	int data;

	/**
	 * Construct a new <code>IntegerToken</code> from the given bytes.  It ignores completely the first two bits.
	 * 
	 * @param byte1
	 *        The first byte.
	 * @param byte2
	 *        The second byte
	 */
	public IntegerToken(byte byte1, byte byte2) {
		super(TokenMap.INTEGER);
		data |= (byte2 & 0xFF);
		data |= ((byte1 & 0x3F) << 8);
		if((data & 0x2000) == 0x2000) {
			data = -0x4000 + data;
		}

	}

	/**
	 * Construct a new <code>IntegerToken</code> from the integer specified.
	 * 
	 * @param i
	 *        The integer this token will represent.
	 */
	public IntegerToken(int i) {
		super(TokenMap.INTEGER);
		data = i % 0x1FFF;
	}

	@Override
	public Integer getData() {
		return data;
	}

	@Override
	public String toString() {
		return new Integer(data).toString();
	}

	@Override
	public void output(OutputStream output) throws IOException {
		int outData = data;
		if(outData < 1) {
			outData = 0x4000 + outData;
		}
		output.write(outData >> 8 & 0x3F);
		output.write(outData & 0xFF);

	}

	@Override
	public Token clone() {
		return new IntegerToken(data);
	}

	@Override
	public int hashCode() {
		return data;
	}

}
